
"""

	Regions, earth regions
	
"""

from google.appengine.ext import db
from google.appengine.ext.db import polymodel

import logging

log = logging.getLogger(__name__)


class Region( db.Model ):
    
    name = db.StringProperty( required = True )
    desc = db.TextProperty()
    
    parent_region = db.SelfReferenceProperty( collection_name="subregions" )
    
    level = db.IntegerProperty( default = 0 )
    
    def get_node( self, level ):
        
        if( level == None or level < 0 or level > 3 ):
            raise Exception( "Wrong level value [%s]" % str(level) )
            
        if( self.level < level ):
            return None
        
        
        def search_level( node ):
            if( node.level == level ): return node
            return search_level( node.parent_region ) 

        return search_level( self )
        
    def check_tree( self, node0, node1, node2 ):
        
        """ check, if the tree is correct, used for check user input, node is actually a node key """
        log.debug( self.key() )
        log.debug( node0 )
        log.debug( node1 )
        log.debug( node2 )
        def chk( level, node ):
            log.debug( "chk %s", self.get_node(level) )
            log.debug( "chk %s", node )
            if( self.get_node(level) ):
                log.debug( "    %s" % self.get_node(level).key() )   
            if( node == None and self.get_node(level) == None ): return True
            if( node == None and level == self.level ): return True
            if( node != None and self.get_node(level) != None 
                    and node == str(self.get_node(level).key()) ): return True
            
            log.debug( node == None and self.get_node(level) == None )    
            log.debug( node == None and level == self.level )
            log.debug( node != None and self.get_node(level) != None
                and node == str(self.get_node(level).key()) )
            return False

        return chk(0,node0) and chk(1,node1) and chk(2,node2) 


    def get_subregions(self):
        return db.GqlQuery("select * from Region WHERE parent_region = :1 order by name", self.key())

    @property
    def waypoints(self):
        return WayPoint.gql("WHERE regions = :1", self.key())
        
def load_regions_for( region ):

    regions = dict()
    
    def add_r( reg ):
    
        if( not regions.has_key(reg.level) or  regions[reg.level] == None ): 
            regions[reg.level] = []

        regions[reg.level].append(reg)
            
    dbregions = Region.gql( "where level = 0 order by name" )

    for r in dbregions:
            add_r( r )
    # if no filter return top level regions
    if( region == None ): return regions
    
    
    for rl in range(0,3):
    
        rn = region.get_node(rl)

        if( rn != None ):
            for r in rn.get_subregions():
                add_r( r )
        else:
            break

    return regions


